define(function(require, exports, module){
	require('jquery');
	require('easyui');
	require('easyui-zh_CN');
	require('basic-css');
	require('common-css');
	require('easyui-default');
	require('easyui-icon');
	
	$.extend($.fn.datagrid.methods, {
		endEditing:function(jq){
			var dg=jq;
			//alert(this);
			var editIndex = dg.data('editIndex');
			//alert(editIndex);
			if (editIndex == undefined){return true;}
			if (dg.datagrid('validateRow', editIndex)){
				dg.datagrid('endEdit', editIndex);
				dg.removeData('editIndex');
				return true;
			} else {
				return false;
			}
			
		},
		append:function(jq,param){
			return jq.each(function(){
				var dg=jq;
				if(dg.datagrid('endEditing')){
					var length=dg.datagrid('getRows').length;
					dg.datagrid('appendRow',param);//新增一行
					dg.data('editIndex',length);
					dg.datagrid('selectRow', length).datagrid('beginEdit',length);//编辑新增行
				}
				//var ed = dg.datagrid('getEditor', {index:dg.editIndex,field:'proTaskName'});
				//$(ed.target).textbox('textbox').focus();//任务名称获得焦点	
			});
		},
		remove:function(jq,param){
			var dg=jq;
			if(dg.datagrid('endEditing')){
				dg.datagrid('deleteRow', param);
			}
		}
	});
	$.extend($.fn.validatebox.defaults.rules, {
		unique:{
	        validator: function(value,param){
	        	//console.log(param);
	        	var editIndex=dg.data('editIndex');
	        	if(editIndex==undefined){
	        		//setTimeout('',200);
	        		return true;
	        	}
	        	var id= dg.datagrid('getRows')[dg.data('editIndex')].id;
	        	var check=$.ajax({
								type: "post",
								contentType:"application/json",
								async:false,
								url: "/authenticated/ajax/boolean/"+param[0],
								data:JSON.stringify({'username':value,'id':id}),
								dataType:"json",
								success: function(result){
									return result;
								},
								error: function(){
									return false;
								}
							}).responseText;
	        	return check=='true';
	        },
	        message: '选项已存在,请重新录入.'
	    }
	});
	var comboboxDatas ;//=[{'id':'enabled','text':'启用'},{'id':'disable','text':'禁用'}]
	var dg;
	var resultObject=$.parseJSON($.ajax({
		type: "post",
		contentType:"application/json",
		async:false,
		url: "/authenticated/grid/column/sys_user_login",
		data:null,
		dataType:"json",
		success: function(result){
			
		},
		error: function(){
			
		}
	}).responseText);
	
	if(resultObject.success){
		comboboxDatas=resultObject.data;
	}else{
		alert(resultObject.message);
	}
	
	var columns=[[
	              {field:'checkbox',checkbox:true},
	              {field:'id',hidden:true},
	              {field:'username',title:'用户名',sortable:true,editor:{
						type:'textbox',options:{required:true,delay:800,validType:['unique["select_username_unique"]']}
					}},
	              {field:'nickname',title:'昵称',sortable:true,editor:{
						type:'textbox'
					}},
	              {field:'status',title:'账号状态',sortable:true,formatter:function(value,row,index){
					  return getComoboxValue('status',value);
				   },editor:{
	            	  type:'combobox',
					  options:{
						  panelHeight:'auto',
						  editable:false,
						  valueField:'code_value',
						  textField:'code_name',
						  data:comboboxDatas.status
							  
					  }
					}},
	              {field:'creator_name',title:'创建人',sortable:true},
	              {field:'create_time',title:'创建日期',sortable:true}
	          ]];
	
	//
	var gridOptions={
		rownumbers:true,
		columns:columns,
		onSortColumn:onSortColumn,
		onDblClickRow:onDblClickRow,//
		checkOnSelect:false,
		multiSort:true//是否启用多列排序
	};
	var paginationOptions={layout:['list','sep','first','prev','sep','manual','sep','next','last','sep','refresh'],
			pageSize:20,
			pageList:[20,50,100],
		    onSelectPage: onSelectPage
	}
	var greidParam={"pageNumber":"1","pageSize":paginationOptions.pageSize};
	$(function(){
		dg=$('#gridList');
		$('#addButton').bind('click', addRow);
		$('#saveButton').bind('click', accept);
		
	    $('#editButton').bind('click', function(){
			alert('easyui');
	    });
	    $('#removeButton').bind('click', function(){
			alert('easyui');
	    });
	    
	    //$('#formSaveButton').bind('click', formSaveButton);
	    //$('#formCancelButton').bind('click', formCancelButton);
	    
	    $.ajax({
			type: "post",
			contentType:"application/json",
			url: "/authenticated/grid/grid_user",
			data:JSON.stringify(greidParam),
			dataType:"json",
			success: function(rsp){
				gridOptions.data=rsp.rows;
				dg.datagrid(gridOptions);
				paginationOptions.total=rsp.total;
				$('#pager').pagination(paginationOptions);
			},
			error: function(){
				alert("error");
			}
		});
	});
    
	
	/*$('#gridList').datagrid(gridOptions);
	$('#pager').pagination({layout:['list','sep','first','prev','sep','manual','sep','next','last','sep'],
		total:10,
		pageSize:1,
		pageList: [1,2,3],
	    onSelectPage: function(pageNumber, pageSize){
	        alert(pageNumber+","+pageSize);
	    }
		});*/
	/*$.ajaxSetup({
		contentType:"application/json"
	});*/
	
	/**
	 * 当点击排序的时候触发
	 * sort：排序的列的字段名
	   order：排序的列的顺序
	 */
	function onSortColumn(sort, order){
		greidParam.sort=sort;
		greidParam.order=order;
		//alert(sort+","+order);
		loadData();
	}
	/**
	 * 当翻页时触发
	 */
	function onSelectPage(pageNumber, pageSize){
		greidParam.pageNumber=pageNumber;
		greidParam.pageSize=pageSize;
    	loadData();
	}
	/**
	 * 双击修改
	 */
	function onDblClickRow(rowIndex,rowData){
		if(dg.data('editIndex')!=rowIndex){
    		if(dg.datagrid('endEditing')){
    			//开始编辑
    			dg.datagrid('selectRow', rowIndex).datagrid('beginEdit', rowIndex);
    			/*var ed = dg.datagrid('getEditor', {index:index,field:field});
				  if(ed){
				  		($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
				 }	*/		
    			//保存编辑行indexrow
				dg.data('editIndex',rowIndex);
    		}
    	}
	}
	//点击保存按钮
	function accept(){
		if (dg.datagrid('endEditing')){
			var rows = dg.datagrid('getChanges');
			var insertedRows = dg.datagrid('getChanges','inserted');
			var params = {};
			if(insertedRows.length>0){
				params.insertedRows=insertedRows;
			}
			$.ajax({
				type: "post",
				contentType:"application/json",
				url: "/authenticated/grid/update/grid_user",
				data:JSON.stringify(params),
				dataType:"json",
				success: function(result){
					if(result.success){
						dg.datagrid('acceptChanges');
					}				
				},
				error: function(){
					alert("error");
				}
			});
		}
	}
	/**
	 * 新增一行
	 */
    function addRow(){
    	var newRowData={creator_name:'admin',create_time:'2016-06-19'};//初始化行数据
    	dg.datagrid('append',newRowData);
    	
    }
	function loadData(){
		$('#gridList').datagrid("loading");
		$.ajax({
			type: "post",
			contentType:"application/json",
			url: "/authenticated/grid/grid_user",
			data:JSON.stringify(greidParam),
			dataType:"json",
			success: function(rsp){
				$('#gridList').datagrid("loadData",rsp.rows);
				$('#gridList').datagrid("loaded");
			},
			error: function(){
				alert("error");
			}
		});
	}
	
	function formCancelButton(){
		$('#formCancelButton').dialog('close')
	}
	/**
	 * 
	 */
    function openFormDialog(){
    	$('#formDialog').dialog('open').dialog('setTitle','新增用户');
    	$('#myForm').form('clear');
    }
    function saveUser(){
    	if($('#myForm').form('validate')){
    		$.ajax({
    			type: "post",
    			contentType:"application/json",
    			url: "/authenticated/grid/grid_user",
    			data:JSON.stringify(greidParam),
    			dataType:"json",
    			success: function(rsp){
    				$('#formDialog').dialog('close');
    				$('#gridList').datagrid("loadData",rsp.rows);
    				$('#gridList').datagrid("loaded");
    			},
    			error: function(){
    				alert("error");
    			}
    		});
    	}
    	
    }
    
});
